<?php

namespace app\api\admin\v1\service\finder;

use app\api\admin\v1\provider\CloudimagesProvider;
use zhanshop\App;
use extend\docker\Images;
use zhanshop\Helper;
use zhanshop\server\Request;
use zhanshop\server\Response;

class Cloudimages extends BaseFinder
{
    protected $page = [
        'first' => false,
        'last' => false,
        'layout' => []
    ];

    protected $headToolbar = [
        [
            'event' => 'add',
            'ico' => '&#xe63c;',
            'title' => '构建',
            'method' => '',
            'page' => './page/docker/create-dockerfile.html',
        ],
        [
            'event' => 'add',
            'ico' => '&#xe601;',
            'title' => '下载',
            'method' => '',
            'page' => '/admin/table.html?_id=Cloudstore',
        ],
    ];

    protected $rowToolbar = [
        [
            'event' => 'add',
            'ico' => '&#xe7ae;',
            'title' => '镜像仓库',
            'method' => '',
            'page' => '/admin/table.html?_id=Cloudstore',
        ],
    ];

    protected function getCols(string $schma){
        return [
            'id' => array (
                'field' => 'id',
                'width' => 170,
                'title' => 'ID',
            ),
            'image_name' => array (
                'field' => 'image_name',
                'title' => '名称',
                'width' => 280
            ),
            'size' => array (
                'field' => 'size',
                'title' => '大小',
                'width' => 170,
            ),
            'create_time' => array (
                'field' => 'create_time',
                'input_type' => 'time',
                'title' => '创建时间',
                'width' => 170
            )
        ];
    }

    public function data(int $page, int $limit, array $order, array $search)
    {
        $list = (new CloudimagesProvider())->getLists();
        return [
            'total' => count($list),
            'list' => $list
        ];
    }

    public function dockerfile(Request $request, Response $response)
    {
        $input = $request->validateRule([
            'Dockerfile' => 'string',
            'volumes' => 'string',
            'mount' => 'string',
            'name' => 'Required',
            'version' => 'Required',
        ])->getData();

        if(preg_match('/^[a-zA-Z0-9_]+$/', $input['name']) == false) App::error()->setError('名称仅能包含字母数字和下划线');
        if(preg_match('/^[a-zA-Z0-9_]+$/', $input['version']) == false) App::error()->setError('版本仅能包含字母数字和下划线');

        $tmpDir = App::runtimePath().'/dockerfile-'.md5(strval(microtime(true)));
        $volumesPath = '/var/www/docker/volumes/'.$input['volumes'].'/_data';
        if($volumesPath == false){
            $volumesPath = '/var/lib/docker/volumes/'.$input['volumes'].'/_data';
        }
        if($input['volumes']){
            Helper::copyDir($volumesPath, $tmpDir);
            $files = explode("CMD ", $input['Dockerfile']);
            $files[0] .= "\nCOPY . ".($input['mount'] ? $input['mount'] : '/var/www')."\n\n";

            $dockerfileData = $files[0];
            $dockerfileData .= isset($files[1]) ? 'CMD '.$files[1] : '';
            $input['Dockerfile'] = $dockerfileData;
        }else{
            mkdir( $tmpDir); // 创建临时目录
        }
        file_put_contents($tmpDir.'/Dockerfile', $input['Dockerfile']);

        try{
            (new Images())->build($tmpDir, $input['name'], $input['version'], function ($client, $data){});
        }catch(\Throwable $err){
            Helper::rmdir($tmpDir);
            App::error()->setError("构建失败,请检查Dockerfile内容是否有错误");
        }

        Helper::rmdir($tmpDir);
        return [];
    }

}
